package com.lhh.company.website.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lhh.company.website.entity.SysDict;
import com.lhh.company.website.service.SysDictService;
import com.lhh.company.website.utils.SysUtils;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j2
@Component
public class SysStartLisener implements ApplicationListener<ApplicationReadyEvent> {

    @Resource
    SysDictService sysDictService;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        log.info("------------------------------->{}","项目启动成功开始加载dict");
        Map<String, SysDict> sysDictMap = new HashMap<String,SysDict>();
        ArrayList<SysDict> fistList = new ArrayList<SysDict>();

        for (int i = 0; i < 5; i++) {
            List<SysDict> list = sysDictService.list(new QueryWrapper<>(SysDict.class)
                    .eq("deep",i)
                    .orderByAsc("orderno")
            );
            for (int j = 0; j < list.size(); j++) {

                SysDict sysDictSub = list.get(j);
                if(sysDictMap.get(sysDictSub.getPId())!=null){
                    sysDictSub.setPName(sysDictMap.get(sysDictSub.getPId()).getName());
                }else{
                    sysDictSub.setPName("顶层");
                }

                if(sysDictSub.getDeep() == 0){
                    fistList.add(sysDictSub);
                }
                sysDictMap.put(sysDictSub.getId(),sysDictSub);
                SysDict PSysDict = sysDictMap.get(sysDictSub.getPId());
                if (PSysDict != null) {
                    PSysDict.getChildren().add(sysDictSub);
                }
            }

        }
        SysUtils.sysDictList.addAll(fistList);
        SysUtils.sysDictMap.putAll(sysDictMap);
        log.info("------------------------------->{}","dict加载完成");
    }
}
